package com.dongye.lxs.chat.utils;

import com.alibaba.dashscope.app.ApplicationResult;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.regex.Pattern;

/**
 * &#064;Description:   消息封装工具类
 * &#064;Date:   2024/7/27 13:00
 * &#064;Author:   李祥生
 */
public final class ContextUtil {


    public static void handleGenerationSseResult(ApplicationResult result, SseEmitter emitter) {
        try {
            String markdown = String.valueOf(result.getOutput().getText());

            // 将Markdown转换为HTML
            String target = MarkdownConverter.convertMarkdownToHtml(markdown);

            // 确保数据中的换行符处理得当
            target = cleanUpNewLines(target);

            // 发送数据
            emitter.send(SseEmitter.event().data(target));
        } catch (Exception e) {
            emitter.completeWithError(e);
        }
    }

    private static String cleanUpNewLines(String input) {
        // 移除多余的换行符，只保留单个换行符
        return input.replaceAll("(?m)^\\s*$", "").replaceAll("\n{2,}", "\n").replace("\n", "<br/>");
    }




}
